<template>
  <div>
    <myDivider name="政府机关管理"></myDivider>
    <!-- <el-alert :closable="false" title="三级菜单1" type="success" /> -->
    <el-page-header @back="goBack" :content="this.operateType == 'update' ? '修改政府机关信息' : '新增政府机关信息'">
    </el-page-header>
    <div class="insertPopulation">


      <el-form ref="insertForm" :model="insertForm" label-width="80px" :rules="insertRules">

        <div style="display: flex;">
          <el-form-item label="名称:" :label-width="formLabelWidth" class="formItemStyle" prop="name">
            <el-input maxlength="30" v-model="insertForm.name" placeholder="请输入名称" autocomplete="off"
              style="width: 262px"></el-input>
          </el-form-item>


          <el-form-item label="上级机关:" :label-width="formLabelWidth" class="formItemStyle">
            <el-select v-model="insertForm.fatherAgenciesData" filterable placeholder="请选择" style="width: 262px;"
              @filter-method="getFatherAgenciesOptionData(name)">
              <el-option v-for="item in fatherAgenciesOptionData" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

        </div>
        <div style="display: flex;">
          <el-form-item label="法定代表人:" :label-width="formLabelWidth" class="formItemStyle">
            <el-input maxlength="5" placeholder="请输入法定代表人" v-model="insertForm.legalRepresentativeName"
              autocomplete="off" style="width: 262px"></el-input>
          </el-form-item>

          <el-form-item label="负责人:" :label-width="formLabelWidth" class="formItemStyle">
            <el-input maxlength="5" placeholder="请输入负责人姓名" v-model="insertForm.responsiblePersonName" autocomplete="off"
              style="width: 262px"></el-input>
          </el-form-item>
        </div>

        <div style="display: flex;">
          <el-form-item label="联系电话:" :label-width="formLabelWidth" class="birthdayDateItemStyle">
            <el-input maxlength="15" placeholder="请输入联系电话" v-model="insertForm.telephoneNumber" autocomplete="off"
              style="width: 254px"></el-input>
          </el-form-item>

          <el-form-item label="统一社会信用代码:" label-width="128px" class="formItemStyle">
            <el-input maxlength="30" placeholder="请输入" v-model="insertForm.socialCreditCode" autocomplete="off"
              style="width: 262px"></el-input>
          </el-form-item>
        </div>



        <div style="display: flex;">

          <el-form-item label="组织类型:" :label-width="formLabelWidth" class="formItemStyle">
            <el-select v-model="insertForm.type" placeholder="请选择" style="width: 262px;">
              <el-option v-for="item in typeOptionData" :key="item.value" :label="item.name" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="发证机关:" :label-width="formLabelWidth" class="formItemStyle">
            <el-input maxlength="30" placeholder="请输入" v-model="insertForm.issuingAuthority" autocomplete="off"
              style="width: 262px"></el-input>
          </el-form-item>
        </div>

        
        <el-form-item label="所在地区:" :label-width="formLabelWidth" class="formItemStyle">
          <el-cascader ref="areas" v-model="insertForm.criCode" @focus="cascaderClick" :props="props" :options="options"
            @change="handleChange" style="width: 666px"></el-cascader>
        </el-form-item>

        <el-form-item label="详细地址:" :label-width="formLabelWidth" class="formItemStyle">
            <el-input placeholder="请输入详细地址" v-model="insertForm.address" autocomplete="off"
              style="width: 666px"></el-input>
          </el-form-item>

        <!-- <el-divider></el-divider> -->



        <el-form-item label="颁发日期:" :label-width="formLabelWidth" class="formItemStyle">
          <el-date-picker type="date" v-model="insertForm.issueDate" style="width:666px;" placeholder="请选择">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="有效期限:" :label-width="formLabelWidth" class="formItemStyle">
          <el-date-picker type="date" v-model="insertForm.effectiveStartDate" style="margin-left:2px;width: 200px;"
            placeholder="开始时间">
          </el-date-picker>~
          <el-date-picker type="date" v-model="insertForm.effectiveEndDate" style="margin-left:2px;width: 200px;"
            placeholder="结束时间">
          </el-date-picker>
        </el-form-item>


        <el-form-item style="float: right; margin-bottom: 80px;">
          <el-button type="primary" @click="onSubmitUpdate" v-if="this.operateType == 'update'">修改</el-button>
          <el-button type="primary" @click="onSubmit" v-if="this.operateType == 'insert'">添加</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>








    </div>
  </div>
</template>





<script>
import {
  getFatherAgencies,
  insertAgency,
  getDictionaryList,
  getAgencyDetail,
  updateAgencyInfo,
  getcityList
} from "./agency";

import {
  getUserList,

} from "../user/user";


export default {
  data() {
    return {
      options: [],
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          let { level } = node
          if (level == 0) {
            getcityList('000000').then(res => {
              let arr = []
              res.forEach(el => {
                arr.push({
                  value: el.criCode,
                  label: el.criName,
                })
              })
              resolve(arr)
            })
          } else {
            getcityList(node.value).then(res => {
              res.forEach(el => {
                el.value = el.criCode
                el.label = el.criName
                el.leaf = level >= 3
              })
              resolve(res)
            })
          }


        }
      },
      formLabelWidth: "120px", //控制前面label的宽度
      insertForm: {
        // 新增弹框参数
        name: "",
        fatherAgenciesData: "",
        legalRepresentativeName: "",
        telephoneNumber: "",
        socialCreditCode: "",
        type: "",
        issuingAuthority: "",
        issueDate: "",
        effectiveStartDate: "",
        effectiveEndDate: "",
        criCode: '',
      },
      insertRules: {
        phoneNumber: [
          {
            required: true,
            message: "手机号不能为空",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "设备名称不能为空",
            trigger: "blur",
          },
        ],
      },
      operateType: 'insert',
      genderListData: [
        { id: '0', name: "女" }, { id: '1', name: "男" }
      ],
      fatherAgenciesOptionData: [],
      typeOptionData: [],
      query: {
        name: "",
        account: ""
      },
      pageNum: 0,
      pageSize: 10,
      totalSize: 0,

    }
  },

  activated() {

    if (this.$route.query.operateType == 'update') {
      this.getAgencyInfo(this.$route.query.id);
      this.operateType = 'update'
    } else {
      this.insertForm = {};
      this.operateType = 'insert'
    }
    this.getZuZhiLeiXing()
    //刚进入页面加载
    this.getFatherAgenciesOptionData("");

  },

  methods: {
    cascaderClick() {
      this.props.lazy = true
      this.options = []
    },
    handleChange(val) {
      console.log(val);
      if (val == undefined) return
      this.insertForm.criCode = val[val.length - 1]
    },
    getZuZhiLeiXing() {
      getDictionaryList("agency_type").then(res => {
        this.typeOptionData = res.data;
      });
    },

    /**
     *  新增
     */
    onSubmit() {
      this.$refs['insertForm'].validate((valid) => { })
      if (this.insertForm.name == undefined || this.insertForm.name == "") {
        return false;
      }

      insertAgency(this.insertForm).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: '新增政府机关信息成功',
            type: 'success'
          });
          this.goBack();
        } else {
          this.$message({
            message: res.message,
            type: "warning",
          });
        }

      })
    },


    /**
     *  修改
     */
    onSubmitUpdate() {
      console.log(this.insertForm, '修改的内容');
      this.insertForm.id = this.$route.query.id;
      updateAgencyInfo(this.insertForm).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.goBack();
        } else {
          this.$message({
            message: res.message,
            type: "warning",
          });
        }

      })
    },

    /**
     *  上一页
     */
    goBack() {
      // this.$router.push({ path: '/agency/management' });
      this.$router.back(-1)
    },

    /**
     * 获取上级机关列表
     */
    getFatherAgenciesOptionData(name) {
      getFatherAgencies(name).then((res) => {
        this.fatherAgenciesOptionData = res.data;
      })
    },


    /**
     * 获取类型字典数据
     */
    getAgencyTypeOptionData() {
      getDictionaryList("agency_type").then((res) => {
        this.typeOptionData = res.data;
      })
    },




    getAgencyInfo(id) {
      getAgencyDetail(id).then(async (res) => {
        console.log(res, '修改的数据');
        // 先不让级联选择器设置为搜索
        this.props.lazy = false
        // 挨个通过code值寻找下级孩子
        let arr = ['000000', res.provinceCriCode, res.cityCriCode, res.districtCriCode, res.criCode]
        let res1 = await getcityList(arr[0])
        let res2 = await getcityList(arr[1])
        let res3 = await getcityList(arr[2])
        let res4 = await getcityList(arr[3])
        let res5 = await getcityList(arr[4])
        // this.options = []
        let aaarr = []
        res1.forEach(el => {
          aaarr.push({
            value: el.criCode,
            label: el.criName,
            children: [],
          })
        })
        aaarr.forEach(el => {
          if (el.value == arr[1]) {
            res2.forEach(item => {
              el.children.push({
                value: item.criCode,
                label: item.criName,
                children: [],
              })
            })
            el.children.forEach(dsc => {
              if (dsc.value == arr[2]) {
                res3.forEach(item => {
                  dsc.children.push({
                    value: item.criCode,
                    label: item.criName,
                    children: [],
                  })
                })
              }
              dsc.children.forEach(dsic => {
                if (dsic.value == arr[3]) {
                  res4.forEach(item => {
                    dsic.children.push({
                      value: item.criCode,
                      label: item.criName,
                    })
                  })
                }
              })
            })
          }
        })
        this.options = aaarr
        this.$set(this.insertForm, 'name', res.name)
        this.$set(this.insertForm, 'fatherAgenciesData', res.pid == 0 ? "" : res.pid)
        this.$set(this.insertForm, 'legalRepresentativeName', res.legalRepresentativeName)
        this.$set(this.insertForm, 'telephoneNumber', res.telephoneNumber)
        this.$set(this.insertForm, 'socialCreditCode', res.socialCreditCode)
        this.$set(this.insertForm, 'type', res.type)
        this.$set(this.insertForm, 'issuingAuthority', res.issuingAuthority)
        this.$set(this.insertForm, 'criCode', res.criCode)
        this.$set(this.insertForm, 'issueDate', res.issueDate)
        this.$set(this.insertForm, 'address', res.address)
        this.$set(this.insertForm, 'effectiveStartDate', res.effectiveStartDate)
        this.$set(this.insertForm, 'effectiveEndDate', res.effectiveEndDate)
        this.$set(this.insertForm, 'responsiblePersonName', res.responsiblePersonName)
      })
    },








  }
};
</script>

<style scoped>
.insertPopulation {
  margin-top: 90px;
  margin-left: 130px;
  height: 50%;
}

.menuTable {
  margin-top: 100px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.menuTable .cell {
  text-align: center;
}

.findValue {
  width: 13%;
  margin-top: 20px;
  margin-left: 15px;
}

.operation {
  margin-right: 50px;
  float: right;
  margin-top: 20px;
}

.formStyle {
  width: 1300px;
  margin: 20px auto;
}

.formItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}

.pageFooter {
  margin-top: 3%;
  margin-left: 40%;
}

.pageFooterFather {
  top: 84%;
  position: relative;
  width: 100%;
}

.el-cascader-menu {
  height: fit-content;
  width: fit-content;
}


.birthdayDateItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}
</style>